<?php
/**
 * Joomla! 1.5 component jhtraq
 *
 * @version $Id: jhtraq.php 2010-03-09 08:28:06 svn $
 * @author JHShop
 * @package Joomla
 * @subpackage jhtraq
 * @license GNU/GPL
 *
 * Traq type system for Joomla
 *
 * This component file was created using the Joomla Component Creator by Not Web Design
 * http://www.notwebdesign.com/joomla_component_creator/
 *
 */


/**
 * TODO:: Split into smaller classes based on tables
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

class JhtraqModelJhtraq extends JModel {
	
	/**
	 * @name __construct
	 * @public
	 * @param none
	 * @return null
	 */
    function __construct() {
		parent::__construct();
		$this->db =& JFactory::getDBO();
    }
	
	/**
	 * @name getModel
	 * @public
	 * @param $model
	 * @return null
	 */
	function getModel($model)
	{
		if(!isset($this->$model))
		$this->$model =& JhtraqHelper::getModel($model);
		return $this->$model;
	}
	
	/**
	 * @name getPagination
	 * @public
	 * @param none
	 * @return pagination object
	 */
	function getPagination()
	{
		return $this->_pagination;
	}
	
	/*** User Related Functions ***/
	
	/**
	 * @name getUserGroups
	 * @public
	 * @param none
	 * @return array
	 * @note wrapper method for JhtraqModelUserGroups::getUserGroups
	 */
	function getUserGroups()
	{
		return $this->getModel('usergroups')->getAll();
// 		return $this->usergroups->getAll();
	}
	
	/**
	 * @name countUsers
	 * @public
	 * @param none
	 * @return int
	 */
	function countUsers()
	{
		return $this->getModel('user')->count();
	}
	
	/**
	 * @name getUser
	 * @public
	 * @param $uid int
	 * @return object user
	 */
	function getUser($uid)
	{
		return $this->getModel('user')->get($uid);
	}
	
	/**
	 * @name getUserList()
	 * @public
	 * @param none
	 * @return array()
	 */
	function getUserList()
	{
		return $this->getModel('user')->getAll();
	}
	
	/**
	 * @name getUsers
	 * @public
	 * @param none
	 * @return array
	 */
	function getUsers()
	{
		$data = $this->getModel('user')->getPaged();
		$this->_pagination = $this->user->getPagination();
		return $data;
	}
	
	/**
	 * @name getMyGroup
	 * @public
	 * @param none
	 * @return array
	 */
	function getMyGroup()
	{
		$user =& JFactory::getUser();
		if(!$user->id)
		{
			$this->db->setQuery("Select *, id as group_id from  #__jhtraq_usergroups where id = '3'");
		}else{
			$this->db->setQuery("Select g.group_id, ug.* from #__jhtraq_users as g left join #__jhtraq_usergroups as ug on g.group_id=ug.id where g.id = '" . $user->id . "'");
		}
		
		$group = $this->db->loadAssoc();
		return $group;
	}
	
	/**
	 * @name getuserPerms
	 * @public
	 * @param $uid int user id
	 * @return object
	 */
	function getUserPerms($uid)
	{
		$this->db->setQuery("Select u.id as user_id, u.*,tu.group_id,ug.* from #__users as u left join #__jhtraq_users as tu on u.id=tu.id left join #__jhtraq_usergroups as ug on tu.group_id = ug.id where u.id='$uid'");
		$res =  $this->db->loadObject();
		return $res;
	}
	
	/**
	 * @name setUserGroup
	 * @public
	 * @param $id int
	 * @param $gid int
	 * @return bool
	 */
	function setUserGroup($id,$gid)
	{
		$this->getModel('user')->setGid($id,$gid);
	}
	
	
	
	/*** RELEASES RELATED ***/
	
	/**
	 * @name getRelease
	 * @public
	 * @param $id
	 * @return Release Object
	 */
	function getRelease($id = 0)
	{
		return $this->getModel('releases')->get($id);
	}
	/**
	 * @name getReleases
	 * @public
	 * @param none
	 * @return array
	 */
	function getReleases()
	{
		$data = $this->getModel('releases')->getPaged();
		$this->_pagination = $this->releases->getPagination();
		return $data;
	}
	
	/**
	 * @name saveRelease
	 * @public
	 * @param $post array
	 * @return bool
	 */
	function saveRelease($post)
	{
		return $this->getModel('releases')->save($post);
	}
	
	
	/*** WIKI RELATED ***/
	
	/**
	 * @name getWikiPage
	 * @public
	 * @param $page
	 * @param $version
	 * @param $pid
	 * @return object
	 */
	function getWikiPage($page,$version,$pid)
	{
		return $this->getModel('wiki')->get($page,$version,$pid);
	}
	
	/**
	 * @name hitWiki
	 * @public
	 * @param $page
	 * @param #$pid
	 * @return bool
	 */
	function hitWiki($page,$pid)
	{
		return $this->getModel('wiki')->hit($page,$pid);
		
	}
	
	/**
	 * @name updateWiki
	 * @public
	 * @param $wiki - wiki db object
	 * @param $post
	 * @param $pid
	 * @return $wiki db object
	 */
	function updateWiki($wiki,$post,$pid)
	{
		return $this->getModel('wiki')->save($wiki,$post,$pid);
	}
	
	/*** Projects ***/
	
	/**
	 * @name countProjects
	 * @public
	 * @param none
	 * @return int
	 */
	function countProjects()
	{
		return $this->getModel('projects')->count();
	}
	
	/**
	 * @name getProject
	 * @public
	 * @param $id
	 * @return $project db object
	 */
	function getProject($id = 0)
	{
		return $this->getModel('projects')->get($id);
	}
	
	/**
	 * @name getProjectbySlug
	 * @public
	 * @param $slug
	 * @return db object $project
	 */
	function getProjectBySlug($slug = 0)
	{
		return $this->getModel('projects')->getSlug($slug);
	}
	
	/**
	 * @name getProjects
	 * @public
	 * @param $publishedOnly - default false
	 * @return array
	 */
	function getProjects($publishedOnly = false)
	{
		$data = $this->getModel('projects')->getPaged($publishedOnly);
		$this->_pagination = $this->projects->getPagination();
		return $data;
	}
	
	/**
	 * @name getProjectList
	 * @public
	 * @param none
	 * @return array
	 */
	function getProjectList()
	{
		return $this->getModel('projects')->getList();
	}
	
	/**
	 * @name saveProject
	 * @public
	 * @param $post
	 * @return bool
	 */
	function saveProject($post)
	{
		return $this->getModel('projects')->save($post);
	}
	
	/**
	 * @name removeProject
	 * @public
	 * @param $ids array
	 * @return bool
	 */
	function removeProject($ids)
	{
		return $this->getModel('projects')->remove($ids);
	}
	
	/*** versions ***/
	
	/**
	 * @name getVersionList
	 * @public
	 * @param none
	 * @return array
	 */
	function getVersionList()
	{
		return $this->getModel('versions')->getList();
	}
	
	/**
	 * @name getVersion
	 * @public
	 * @param $id int
	 * @return db object
	 */
	function getVersion($id = 0)
	{
		return $this->getModel('versions')->get($id);
	}
	
	/**
	 * @name getVersions
	 * @public
	 * @param none
	 * @return array
	 */
	function getVersions()
	{
		$data = $this->getModel('versions')->getPaged();
		$this->_pagination = $this->versions->getPagination();
		return $data;
	}
	
	/**
	 * @name removeVersion
	 * @public
	 * @param $ids
	 * @return bool
	 */
	function removeVersion($ids)
	{
		return $this->getModel('versions')->remove($ids);
	}
	
	/**
	 * @name saveVersion
	 * @public
	 * @param $post
	 * @return bool
	 */
	function saveVersion($post)
	{
		return $this->getModel('versions')->save($post);
	}
	
	/*** milestones ***/
	
	/**
	 * @name getMilestone
	 * @public
	 * @param $id
	 * @return db object
	 */
	function getMilestone($id = 0)
	{
		return $this->getModel('milestones')->get($id);
	}
	
	/**
	 * @name getMilestones
	 * @public
	 * @param none
	 * @return array
	 */
	function getMilestones()
	{
		$data = $this->getModel('milestones')->getPaged();
		$this->_pagination = $this->milestones->getPagination();
		return $data;
	}
	
	/**
	 * @name saveMilestone
	 * @public
	 * @param $post
	 * @return bool
	 */
	function saveMilestone($post)
	{
		return $this->getModel('milestones')->save($post);
	}
	
	/**
	 * @name removeMilesone
	 * @public
	 * @param $ids
	 * @return bool
	 */
	function removeMilestone($ids)
	{
		return $this->getModel('milestones')->remove($ids);
	}
	
	/**
	 * @name getMilestonesByProject
	 * @public
	 * @param $id
	 * @return array
	 */
	function getMilestonesByProject($id)
	{
		return $this->getModel('milestones')->getByProject($id);
	}
	
	
	/**
	 * @name getchangelogMilestone
	 * @public
	 * @param $pid
	 * @return array
	 * @TODO Abstract to correct class files
	 */
	function getChangelogMilestones($pid)
	{
		$milestones = array();
		$this->db->setQuery("SELECT id,milestone,completed,changelog FROM #__jhtraq_milestones WHERE project_id='".$pid."' AND completed > 0 ORDER BY completed DESC");
		$rows = $this->db->loadAssocList();
		foreach($rows as $row)
		{
			$row['changes'] = array();
			$row['changelog'] = JhtraqHelper::formattext($info['changelog']);
			$this->db->setQuery("SELECT id,summary,status,type FROM #__jhtraq_tickets WHERE milestone_id='".$row['id']."' ORDER BY summary ASC");
			$changes = $this->db->loadAssocList();
			foreach($changes as $change)
			{
				$row['changes'][] = $change;
			}
			$milestones[] = $row;
		}
		return $milestones;
	}
	
	
	
	/**** STILL TO SORT OUT TODOS ****/
	
	
	
	
	function countTickets()
	{
		$this->db->setQuery("Select count(*) as rows from #__jhtraq_tickets");
		return (int)$this->db->loadResult();
	}
	
	
	/** @depreciated **/
	function getConfig()
	{
		$this->db->setQuery("Select `setting`,`value` from #__jhtraq_settings");
		$list =  $this->db->loadAssocList();
		$return = array();
		foreach($list as $item)
		{
			$return[$item['setting']] = $item['value'];
		}
		return $return;
	}
	
	/** @depreciated **/
	function saveConfig($cfg)
	{
// 		print_r($cfg);
		foreach($cfg as $k=>$v)
		{
			$this->db->setQuery("Update #__jhtraq_settings set `value`='".$this->db->getEscaped($v)."' where `setting`='$k'");
			$this->db->query();
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	function getComponent($id = 0)
	{
		$this->db->setQuery("Select * from #__jhtraq_components where id='$id'");
		return $this->db->loadObject();
	}
	
	
	
	
	
	
	
	function getComponents()
	{
		$mainframe =& JFactory::getApplication();
		$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		jimport('joomla.html.pagination');
		$search = JRequest::getVar('search');
		$project = (int)JRequest::getVar('project');
		
		$query = "Select SQL_CALC_FOUND_ROWS * from #__jhtraq_components";
		if($search != '')
		$query .= "Where name like'%$search%' ";
		if($project > 0 && $search != '')
		{
			$query .= " AND project_id='$project'";
		}elseif($project > 0 && $search == '')
		{
			$query .= " Where project_id='$project'";
		}
		
		$query .= ' ORDER BY name ASC';
		
		$this->db->setQuery($query,$limitstart, $limit );
		$r =&$this->db->loadAssocList();
// 		print_r($this->db);
		
		$this->db->setQuery('SELECT FOUND_ROWS();');
		$this->_pagination = new JPagination( $this->db->loadResult(), $limitstart, $limit );
		
		return $r;
	}
	
	
	
	
	
	
	
	
	

	
	
	function getTypes()
	{
		$this->db->setQuery("SELECT * FROM #__jhtraq_ticket_types ORDER BY name ASC");
		$res = $this->db->loadAssocList();
		$rows = array();
		foreach($res as $row)
		{
			$rows[$row['id']] = $row;
		}
		return $rows;
	}
	
	function getStatuses()
	{
		$this->db->setQuery("SELECT * FROM #__jhtraq_ticket_status ORDER BY name ASC");
		return $this->db->loadAssocList();
	}
	
	function getPriorities()
	{
		$this->db->setQuery("SELECT * FROM #__jhtraq_priorities ORDER BY name ASC");
		return $this->db->loadAssocList();
	}
	
	function getSeverities()
	{
		$this->db->setQuery("SELECT * FROM #__jhtraq_severities ORDER BY name ASC");
		return $this->db->loadAssocList();
	}
	
	function removeType($id)
	{
		$this->db->setQuery("Delete FROM #__jhtraq_ticket_types where id='$id'");
		return $this->db->query();
	}
	
	function updateTypes($post, $name='',$bullet='')
	{
		foreach($post as $id => $values)
		{
			// Make sure the value isnt empty.
			if(!empty($values['name']))
			{
				$this->db->setQuery("UPDATE #__jhtraq_ticket_types SET name='".$this->db->getEscaped($values['name'])."', bullet='".$this->db->getEscaped($values['bullet'])."' WHERE id='".(int)$id."' LIMIT 1");
				$this->db->query();
			}
		}
		
		// Check if we're adding one as well...
		if(!empty($name))
		$this->db->setQuery("INSERT INTO  #__jhtraq_ticket_types (name,bullet) VALUES('".$this->db->getEscaped($name)."','".$this->db->getEscaped($bullet)."')");
		$this->db->query();
	}
	
	function removeStatus($id)
	{
		$this->db->setQuery("Delete FROM #__jhtraq_ticket_status where id='$id'");
		return $this->db->query();
	}
	
	function updateStatuses($post, $name='',$status='')
	{
		foreach($post as $id => $values)
		{
			// Make sure the value isnt empty.
			if(!empty($values['name']))
			{
				$this->db->setQuery("UPDATE #__jhtraq_ticket_status SET name='".$this->db->getEscaped($values['name'])."', status='".$this->db->getEscaped($values['status'])."' WHERE id='".(int)$id."' LIMIT 1");
				$this->db->query();
			}
		}
		
		// Check if we're adding one as well...
		if(!empty($name))
		$this->db->setQuery("INSERT INTO  #__jhtraq_ticket_status (name,status) VALUES('".$this->db->getEscaped($name)."','".$this->db->getEscaped($status)."')");
		$this->db->query();
	}
	
	function removePriority($id)
	{
		$this->db->setQuery("Delete FROM #__jhtraq_priorities where id='$id'");
		return $this->db->query();
	}
	
	function updatePriorities($post, $name='')
	{
		foreach($post as $id => $values)
		{
			// Make sure the value isnt empty.
			if(!empty($values['name']))
			{
				$this->db->setQuery("UPDATE #__jhtraq_priorities SET name='".$this->db->getEscaped($values['name'])."' WHERE id='".(int)$id."' LIMIT 1");
				$this->db->query();
			}
		}
		
		// Check if we're adding one as well...
		if(!empty($name))
		$this->db->setQuery("INSERT INTO  #__jhtraq_priorities (name) VALUES('".$this->db->getEscaped($name)."')");
		$this->db->query();
	}
	
	function removeSeverity($id)
	{
		$this->db->setQuery("Delete FROM #__jhtraq_severities where id='$id'");
		return $this->db->query();
	}
	
	function updateSeverities($post, $name='')
	{
		foreach($post as $id => $values)
		{
			// Make sure the value isnt empty.
			if(!empty($values['name']))
			{
				$this->db->setQuery("UPDATE #__jhtraq_severities SET name='".$this->db->getEscaped($values['name'])."' WHERE id='".(int)$id."' LIMIT 1");
				$this->db->query();
			}
		}
		
		// Check if we're adding one as well...
		if(!empty($name))
		$this->db->setQuery("INSERT INTO  #__jhtraq_severities (name) VALUES('".$this->db->getEscaped($name)."')");
		$this->db->query();
	}
	

	
	
	
	
	
	
	
	
	
	
	
	function removeComponent($ids)
	{
		if(!is_array($ids))
		$ids = array();
		$this->db->setQuery("Delete from #__jhtraq_components where id in(".implode(",",$ids) . ")");
		return $this->db->query();
	}
	
	function saveComponent($post)
	{
		$id = (int)$post['id'];
		$name = $this->db->getEscaped($post['name']);
		$project_id = (int)$post['project_id'];
		
		$q = "Set Name='$name',project_id='$project_id'";
		if($id > 0)
		{
			//update
			$query = "Update #__jhtraq_components " . $q . " where id='$id'";
		}else{
			//insert
			$query = "Insert into #__jhtraq_components " . $q;
		}
		$this->db->setQuery($query);
		return $this->db->query();
	}
	
	
	
	
	

	
	
	
	
	
	
	function getTicketTickets($pid, $query = '', $sort = 'id', $order = 'desc')
	{
		// Get Tickets
		$tickets = array();
		
		//pagination
		$mainframe =& JFactory::getApplication();
		$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( 'jhtraqticketlimitstart'.$pid, 'limitstart', 0, 'int' );
		jimport('joomla.html.pagination');
		//$this->db->setQuery($query,$limitstart, $limit );
		$this->db->setQuery("SELECT SQL_CALC_FOUND_ROWS * FROM #__jhtraq_tickets WHERE project_id='".$pid ."' $query ORDER BY $sort $order",$limitstart,$limit);
		$rows = $this->db->loadAssocList();
		$this->db->setQuery('SELECT FOUND_ROWS();');
		$this->_pagination = new JPagination( $this->db->loadResult(), $limitstart, $limit );
		foreach($rows as $info)
		{
			$info['summary'] = stripslashes($info['summary']); // Strip the slahes from the summary field
			$info['body'] = stripslashes($info['body']); // Strip the slahes from the body field
			
			$this->db->setQuery("SELECT * FROM #__jhtraq_components WHERE id='".(int)$info['component_id']."' LIMIT 1");
			$info['component'] = $this->db->loadAssoc(); //component information
			$this->db->setQuery("SELECT * FROM #__users u  left join #__jhtraq_users ju on u.id=ju.id WHERE u.id='".(int)@$info['owner_id']."' LIMIT 1"); // owner infor
			$info['owner'] = $this->db->loadAssoc();
			$this->db->setQuery("SELECT * FROM #__jhtraq_milestones WHERE id='".(int)$info['milestone_id']."' LIMIT 1");
			$info['milestone'] = $this->db->loadAssoc();// Get Milestone info
			//$this->db->setQuery("SELECT * FROM #__jhtraq_versions WHERE id='".(int)$info['version_id']."' LIMIT 1");
			//$info['version'] = $this->db->loadAssoc();
			$info['version'] = $this->getModel('versions')->get((int)$info['version_id'],'loadAssoc');
			$this->db->setQuery("SELECT * FROM #__users u  left join #__jhtraq_users ju on u.id=ju.id WHERE u.id='".(int)$info['assigned_to']."' LIMIT 1");
			$info['assignee'] = $this->db->loadAssoc();
			$tickets[] = $info;
		}
		
		return $tickets;
	}
	
	
	
	function fetchTimelineByProject($id)
	{
		$days = array();
                $mainframe =& JFactory::getApplication();
		$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		jimport('joomla.html.pagination');

		$query = "SELECT SQL_CALC_FOUND_ROWS DISTINCT YEAR(date) AS 'year', MONTH(date) AS 'month', DAY(date) AS 'day', date, timestamp FROM #__jhtraq_timeline WHERE project_id='".$id."' GROUP BY YEAR(date), MONTH(date), DAY(date) ORDER BY date DESC";

                $this->db->setQuery($query,$limitstart, $limit );
		$res =&$this->db->loadAssocList();
		//print_r($this->db);

		$this->db->setQuery('SELECT FOUND_ROWS();');
		$this->_pagination = new JPagination( $this->db->loadResult(), $limitstart, $limit );
		//$res = $this->db->loadAssocList();
	
		foreach($res as $dayinfo)
		{
			$day = array();
			$day['date'] = $dayinfo['date'];
			$day['timestamp'] = $dayinfo['timestamp'];
			$day['changes'] = array();
			
			// Fetch changes
			$this->db->setQuery("SELECT * FROM #__jhtraq_timeline WHERE project_id='".$id."' AND date='".$dayinfo['date']."' ORDER BY timestamp DESC");
			$fc = $this->db->loadAssocList();

			foreach($fc as $changeinfo)
			{
				if($changeinfo['action'] == 'open_ticket' || $changeinfo['action'] == 'close_ticket' || $changeinfo['action'] == 'reopen_ticket')
					{
						$ticketinfo = $this->ticketGet(array('id'=>$changeinfo['owner_id']));
						//print_r($ticketinfo);
						$day['changes'][] = array(
						'text' => JhtraqHelper::l('timeline_'.$changeinfo['action'],$changeinfo['user_name'],$ticketinfo['ticket_id'],$ticketinfo['summary']),
												  'timestamp' => $changeinfo['timestamp'],
												  'url' => JRoute::_("index.php?option=com_jhtraq&view=tickets&project=".JRequest::getVar('project').'&layout=view&ticket='.$ticketinfo['ticket_id'])
												  );
					}
					
					if($changeinfo['action'] == 'create_wikipage' || $changeinfo['action'] == 'edit_wikipage')
					{
						$day['changes'][] = array(
						'text' => $changeinfo['user_name'] . ' ' . JText::_(strtoupper('timeline_'.$changeinfo['action'])) .'('.$changeinfo['data'].')',
						'timestamp' => $changeinfo['timestamp'],
						'url' => JRoute::_("index.php?option=com_jhtraq&view=wiki&project=".JRequest::getVar('project')."&page=".$changeinfo['data'])
						);
					}
			}
			
			$days[] = $day;
		}
		return $days;
	}
	
	public function ticketGet($args)
	{
		
		if(!array($args))
		{
			$args = func_get_args();
		}
// 		print_r($args);
		// Check which arguments are set and compile the query.
		$query = array();
		
		if(isset($args['id']))
		$query[] = "id='".$args['id']."'";
		
		if(isset($args['ticket_id']))
		$query[] = "ticket_id='".$args['ticket_id']."'";
		
		if(isset($args['project_id']))
		$query[] = "project_id='".$args['project_id']."'";
		
		// Build the arguments query block.
		$query = implode(' AND ',$query);
// 		die($query);
		
		$this->db->setQuery("SELECT * FROM #__jhtraq_tickets WHERE $query LIMIT 1");
		$ticket = $this->db->loadAssoc();
		$ticket['milestone'] = $this->getModel('milestones')->get((int)$ticket['milestone_id'], 'loadAssoc');
		$ticket['version'] = $this->getModel('versions')->get((int)$ticket['version_id'],'loadAssoc');
		
		$this->db->setQuery("SELECT * FROM #__jhtraq_components WHERE id='".(int)$ticket['component_id']."' LIMIT 1");
		$ticket['component'] = $this->db->loadAssoc();
		$this->db->setQuery("SELECT * FROM #__users u  left join #__jhtraq_users ju on u.id=ju.id WHERE u.id='".(int)$ticket['assigned_to']."' LIMIT 1");
		$ticket['assignee'] = $this->db->loadAssoc();
		$this->db->setQuery("Select * from #__jhtraq_attach where ticket_id='".(int)$ticket['ticket_id']."' and project_id='".(int)$ticket['project_id']."'");
		$ticket['attachments'] = $this->db->loadAssocList();
		$this->db->setQuery("select * from #__jhtraq_ticket_history where ticket_id='".(int)$ticket['id']."' and project_id='".(int)$ticket['project_id'] . "'");
		$ticket['changes'] = $this->db->loadAssocList();
		//print_r($this->db);
		return $ticket;

	}
	
	
	function saveTicket($data,$project)
	{
		$user =&JFactory::getUser();
		
		$errors = false;
		// Check fields for errors.
		if(empty($data['summary']))
		{
			$this->setError(JText::_('error_summary_empty'));
			$errors = true;
		}
		// Check body
		if(empty($data['body']))
		{
			$this->setError(JText::_('error_body_empty'));
			$errors = true;
		}
		
		
		if(empty($data['name']) && !$user->id)
		{
			$this->setError(JText::_('error_name_empty'));
			$errors = true;
		}
		
		// If theres errors, push them to the error
		// array and return false.
		if($errors)
		{
			return false;
		}
		
		if(!isset($data['created']))
			$data['created'] = time();
		
		$id = $data['id'];
		$next_ticket_id = $project->next_tid;
		if($next_ticket_id == 0)
			$next_ticket_id++;
		$summary = $this->db->getEscaped($data['summary']);
		$body = $this->db->getEscaped($data['body']);
		$user_id = (int)$user->id;
		$user_name = isset($user->username)?$user->username:$data['name'];
		$project_id = $project->id;
		$milestone_id = $data['milestone'];
		$version_id = $data['version'];
		$component_id = $data['component'];
		$type = $data['type'];
		
		$status = 1;
		
		$priority = $data['priority'];
		$severity = $data['severity'];
		$assigned_to = $data['assigned_to'];
		$closed = 0;
		$created = $data['created'];
		$private = isset($data['private'])?$data['private']:0;
		
		// Sort out the data fields and values for the query.
		$sets = "summary='$summary',body='$body',user_id='$user_id',user_name='$user_name',project_id='$project_id',milestone_id='$milestone_id',
		version_id='$version_id',component_id='$component_id',type='$type',status='$status',priority='$priority',severity='$severity',assigned_to='$assigned_to',closed='$closed',private='$private'";
		$q = "Insert into  #__jhtraq_tickets set ticket_id = '$next_ticket_id',created='$created'," . $sets;
						
		$this->db->setQuery($q);
		$this->db->query();
	//	print_r($this->db);
	//	die();
		
		$ticketid = $this->db->insertid();
		
		// Insert the ticket history row
		$this->db->setQuery("INSERT INTO #__jhtraq_ticket_history (user_id,user_name,timestamp,ticket_id,project_id,changes,comment) VALUES(
			'".$user_id."',
			'".$user_name."',
			'".time()."',
			'".$ticketid."',
			'".$project_id."',
			'".json_encode(array(array('property'=>'status','from'=>'','to'=>'1','action'=>'open')))."',
			''
		)");
		$this->db->query();
		// Insert the timeline row
		$this->db->setQuery("INSERT INTO #__jhtraq_timeline VALUES(
			0,
			'".$project_id."',
			'".$ticketid."',
			'open_ticket',
			'".$next_ticket_id."',
			'".$user_id."',
			'".$user_name."',
			'".time()."',
			NOW()
		)");
		$this->db->query();
		// Set the ticket ID.
		$ret_ticket_id = $next_ticket_id;
		$next_ticket_id++;
		// Update Project's 'next_tid' field.
		$this->db->setQuery("UPDATE #__jhtraq_projects SET next_tid='$next_ticket_id' WHERE id='".$project_id."' LIMIT 1");
		$this->db->query();
		
		//Ok we need to mail this ticket!!!!
		//1) get the project admins!
		$managers = explode(",", $project->managers);
		if(count($managers))
		{
			$this->db->setQuery("Select * from #__users where id in (".$project->managers.")");
			$mails = array();
			$res = $this->db->loadObjectList();
			if(count($res))
			{
				foreach($res as $u)
				{
					$mails[] = $u->email;
				}
				$body = JText::_('COM_JHTRAQ_NEW_TICKET_BODY');
				$bodylink = JRoute::_('index.php?option=com_jhtraq&project='.$project->slug.'&view=tickets&layout=view&ticket='.$ret_ticket_id,false,0);
				$uri             =& JURI::getInstance();
				static $prefix;
				if ( ! $prefix ) {
					$prefix = $uri->toString( array('host', 'port'));
					//$prefix .= JURI::base(true);
				}
				if ( ! preg_match('#^/#', $bodylink) ) {
					$bodylink =  '/' . $bodylink;
				}
				
				$bodylink       = 'http://' . $prefix . $bodylink;
				
				
				//                              $bodylink = substr($bodylink,0,-1);
				//                              $bodylink = str_replace("administrator/", "". JURI::base()) . $bodylink;
				
				//Ok we need to replace variables!!!
				
				$body = str_replace("{TICKETLINK}", $bodylink, $body);
				$body = str_replace("{TICKETTITLE}", $data['summary'], $body);
				$body = str_replace("{TICKETAUTHOR}", $user_name, $body);
				$body = str_replace("{TICKETPROJECT}", $project->name,$body);
				
				$subject = JText::_('COM_JHTRAQ_NEW_TICKET_SUBJECT');
				$subject = str_replace('{TICKETPROJECT}',$project->name, $subject);
				
				JhtraqHelper::sendMail($mails,$subject,$body,true);
			}
		}
		return $ret_ticket_id;
	}
	
	
	public function deleteTicket($id)
	{
				//die($id);
		// Delete ticket
		$this->db->setQuery("DELETE FROM #__jhtraq_tickets WHERE id='".$id."' LIMIT 1");
		$this->db->query();
		// Delete ticket history
		$this->db->setQuery("DELETE FROM #__jhtraq_ticket_history WHERE ticket_id='".$id."'");
		$this->db->query();
		// Delete timeline references
		$this->db->setQuery("DELETE FROM #__jhtraq_timeline WHERE owner_id='".$id."' AND (action='open_ticket' OR action='reopen_ticket' OR action='close_ticket')");
		$this->db->query();
	}
	
	function ticket_type($type_id)
	{
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_ticket_types WHERE id='".$type_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function ticket_priority($priority_id)
	{
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_priorities WHERE id='".$priority_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function ticket_severity($severity_id)
	{
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_severities WHERE id='".$severity_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function ticket_status($status_id)
	{
		if($status_id == 0)
		return JText::_('Unconfirmed');
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_ticket_status WHERE id='".$status_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function updateticket($ticket,$project)
	{
	//	print_r($_POST);
	//	die();
		$changes = array();
		$querybits = array();
		//$user =& JFactory::getUser();
		$user = $this->getModel('user')->getCurrent();

		$errors = array();

	if(empty($_POST['private']))
		$_POST['private'] = $ticket['private'];
	
	if(!count($errors))
	{
		// Type
		if($_POST['type'] != $ticket['type'])
		{
			$querybits[] = "type='".$_POST['type']."'";
			$changes[] = array('property'=>'type','from'=>$this->ticket_type($ticket['type']),'to'=>$this->ticket_type($_POST['type']));
		}
		// Priority
		if($_POST['priority'] != $ticket['priority'])
		{
			$querybits[] = "priority='".$_POST['priority']."'";
			$changes[] = array('property'=>'priority','from'=>$this->ticket_priority($ticket['priority']),'to'=>$this->ticket_priority($_POST['priority']));
		}
		// Milestone
		if($_POST['milestone'] != $ticket['milestone_id'])
		{
			$querybits[] = "milestone_id='".$_POST['milestone']."'";
			$newmilestone = $this->getMilestone($_POST['milestone']);
			$changes[] = array('property'=>'milestone','from'=>$ticket['milestone']['milestone'],'to'=>$newmilestone->milestone);
		}
		// Component
		if($_POST['component'] != $ticket['component_id'])
		{
			$querybits[] = "component_id='".$_POST['component']."'";
			$newcomponent = $this->getComponent($_POST['component']);
			$changes[] = array('property'=>'component','from'=>$ticket['component']['name'],'to'=>$newcomponent->name);
		}
		// Assigned to
		if($_POST['assign_to'] != $ticket['assigned_to'])
		{
			$querybits[] = "assigned_to='".$_POST['assign_to']."'";
			$newassignee = $this->getUser($_POST['assign_to']);
			$changes[] = array('property'=>'assigned_to','from'=>$ticket['assignee']['username'],'to'=>$newassignee->username);
		}
		// Severity
		if($_POST['severity'] != $ticket['severity'])
		{
			$querybits[] = "severity='".$_POST['severity']."'";
			$changes[] = array('property'=>'severity','from'=>$this->ticket_severity($ticket['severity']),'to'=>$this->ticket_severity($_POST['severity']));
		}
		// Version
		if($_POST['version'] != $ticket['version_id'])
		{
			$querybits[] = "version_id='".$_POST['version']."'";
			$newversion = $this->getVersion($_POST['version']);
			$changes[] = array('property'=>'version','from'=>$ticket['version']['version'],'to'=>$newversion->version);
		}
		// Summary
		if($_POST['summary'] != $ticket['summary'])
		{
			$querybits[] = "summary='".$_POST['summary']."'";
			$changes[] = array('property'=>'summary','from'=>$ticket['summary'],'to'=>$_POST['summary']);
		}
		// Private ticket
		elseif($_POST['private'] != $ticket['private'])
		{
			$querybits[] = "private='".$_POST['private']."'";
			$changes[] = array('property'=>'private','from'=>$ticket['private'],'to'=>$_POST['private'],'action'=>($_POST['private'] ? 'private' : 'public'));
		}
		// Action
		if($_POST['action'] == 'mark' && $ticket['status'] != $_POST['mark_as'])
		{
			$querybits[] = "status='".$_POST['mark_as']."'";
			$changes[] = array('property'=>'status','from'=>$this->ticket_status($ticket['status']),'to'=>$this->ticket_status($_POST['mark_as']),'action'=>'mark');
		}
		elseif($_POST['action'] == 'close' && $ticket['status'] != $_POST['close_as'])
		{
			$querybits[] = "status='".$_POST['close_as']."'";
			$querybits[] = "closed='1'";
			$changes[] = array('property'=>'status','from'=>$this->ticket_status($ticket['status']),'to'=>$this->ticket_status($_POST['close_as']),'action'=>'close');
			
			// Insert timeline row
			$this->db->setQuery("INSERT INTO #__jhtraq_timeline (project_id,owner_id,action,data,user_id,user_name,timestamp,date) VALUES(
				'".$project->id."',
				'".$ticket['id']."',
				'close_ticket',
				'".$ticket['ticket_id']."',
				'".$user->id."',
				'".($user->id ? $user->username : $_POST['name'])."',
				'".time()."',
				NOW()
			)");
			$this->db->query();
		}
		elseif($_POST['action'] == 'reopen' && $ticket['status'] != $_POST['reopen_as'])
		{
			$querybits[] = "status='".$_POST['reopen_as']."'";
			$querybits[] = "closed='0'";
			$changes[] = array('property'=>'status','from'=>$this->ticket_status($ticket['status']),'to'=>$this->ticket_status($_POST['reopen_as']),'action'=>'reopen');
			
			// Insert timeline row
			$this->db->setQuery("INSERT INTO #__jhtraq_timeline (project_id,owner_id,action,data,user_id,user_name,timestamp,date) VALUES(
				'".$project->id."',
				'".$ticket['id']."',
				'reopen_ticket',
				'".$ticket['ticket_id']."',
				'".$user->id."',
				'".($user->id ? $user->username : $_POST['name'])."',
				'".time()."',
				NOW()
			)");
			$this->db->query();
		}
	

		if(count($changes) > 0 || $_POST['comment'] != '')
		{
			//modified timeline
			$querybits[] = "updated='".time()."'";
			// Update the ticket
			if(count($changes) > 0)
			$this->db->setQuery("UPDATE #__jhtraq_tickets SET ".implode(', ',$querybits)." WHERE id='".$ticket['id']."' LIMIT 1");
			$this->db->query();
			
			// Set guest name cookie
			
			// Insert row into ticket history
			$this->db->setQuery("INSERT INTO #__jhtraq_ticket_history (user_id,user_name,timestamp,ticket_id,project_id,changes,comment) VALUES(
				'".$user->id."',
				'".($user->id ? $user->username : $_POST['name'])."',
				'".time()."',
				'".$ticket['id']."',
				'".$project->id."',
				'".json_encode($changes)."',
				'".$this->db->getEscaped($_POST['comment'])."'
			)");
			$this->db->query();
			return true;
		}
	}
}

}
?>